package com.rchat.pocmini.wxapi;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.global.UrlsGlobal;
import com.rchat.pocmini.util.HttpUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.json.JSONObject;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by ljd on 2017/2/15.
 *
 * 申请睿洽支付流水单号
 *
 * @deprecated 此类不再使用
 */

public class ApplyRchatTradeNoTask extends AsyncTask <String, Integer, String>{

    private static final String TAG = "ApplyRchatTradeNoTask";

    private Context context;
    private IWXAPI iwxapi;
    //要支付的金额，单位分
    private String money;
    //商品名称
    private String goodsName;

    //商品类型 1.月，2.年
    private int tradeTypeId;

    private boolean isFromLoginActivity = false;
    private String account;

    public ApplyRchatTradeNoTask(Context context,IWXAPI iwxapi,String money,String goodsName,int tradeTypeId,String account,boolean isFromLoginActivity){
        this.context = context;
        this.iwxapi = iwxapi;
        this.money = money;
        this.goodsName = goodsName;
        this.tradeTypeId = tradeTypeId;
        this.isFromLoginActivity = isFromLoginActivity;
        this.account = account;
    }

    @Override
    protected void onPreExecute() {
        Toast.makeText(context, "获取订单中...", Toast.LENGTH_SHORT).show();
        super.onPreExecute();
    }
    @Override
    protected String doInBackground(String... strings) {
        String result = null;
        String requestJson = createRechargeTicket(Float.parseFloat(money)/100 + "",goodsName,tradeTypeId);
        result = HttpUtil.httpConnect(UrlsGlobal.getUrl(UrlsGlobal.APPLY_RCHAT_TRADE_NO_URL),requestJson,HttpUtil.HTTP_POST);
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result==null){
            return;
        }
        try {
            JSONObject json = new JSONObject(result);
            if(!json.getString("code").equals("200")) {
                Toast.makeText(context, json.getString("desc"), Toast.LENGTH_SHORT).show();
                return;
            }
            JSONObject data = json.getJSONObject("data");
            //开始支付
            PayReq req = new PayReq();
            req.appId			= Constants.APP_ID;//appid
            req.partnerId		= Constants.PARTNER_ID;//mch_ID
            req.prepayId		= data.getString("prepayid");//预支付订单号
            req.nonceStr		= data.getString("noncestr");//nonce_str
            req.timeStamp		= Constants.genTimeStamp();//时间戳
            req.packageValue	= Constants.PACKAGE;//常量，Sign=WXpay
            req.extData			= "app data"; // optional
//            req.sign            = data.getString("sign");
            //生成签名
            SortedMap<Object, Object> params = new TreeMap<>();
            params.put("appid",     req.appId);
            params.put("partnerid", req.partnerId);
            params.put("noncestr",  req.nonceStr);
            params.put("package",   req.packageValue);
            params.put("prepayid",  req.prepayId);
            params.put("timestamp", req.timeStamp);
            req.sign			= Constants.createSign(params);

//            Log.e(TAG,"req.prepayId:" + json.getString("prepayid"));
//            Log.e(TAG,"req.nonceStr:" + json.getString("noncestr"));
//            Log.e(TAG,"req.sign:" + json.getString("sign"));


            Toast.makeText(context, "准备支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            iwxapi.sendReq(req);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 申请支付流水
     * @param goodsName 商品名称
     * @param price 价格，单位分
     * @return
     */
    private String createRechargeTicket(String price,String goodsName,int tradeTypeId){
        StringBuilder sb = new StringBuilder();
        sb.append("{").append("\"code\"").append(":").append("\"1051\"").append(",")
                .append("\"signature\"").append(":").append("\" \"").append(",")
                .append("\"data\"").append(":").append("{");
                if(isFromLoginActivity) {
                    sb.append("\"account\"").append(":").append("\"").append(account).append("\",");
                }else {
                    sb.append("\"userName\"").append(":").append("\"").append(PocAccount.getUserId()).append("\",");
                }
                sb.append("\"goodsName\"").append(":").append("\"").append(goodsName) .append("\",")
                .append("\"price\"").append(":").append("\"").append(price) .append("\",")
                .append("\"tradeTypeId\"").append(":").append("\"").append(tradeTypeId) .append("\",")
                .append("\"tradeType\"").append(":").append("\"").append("App") .append("\"")
                .append("}")
                .append("}");
        return sb.toString();
    }
}
